package cn.tedu.mall.seckill.interceptor;

import cn.tedu.mall.common.exception.CoolSharkServiceException;
import cn.tedu.mall.common.restful.ResponseCode;
import cn.tedu.mall.pojo.seckill.dto.SeckillOrderAddDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

@Component
//留出扩展空间,定义order顺序,有step
@Order(1)
public class ReSeckillInterceptor implements SeckillInterceptor {
    /**
     * 定义重复秒杀,同一个人,秒杀下单抢购了同一个sku 就是重复秒杀
     * 将userId和skuId组合成一个key值,只要满足同一个,且同一个商品,key值相同的
     * 在redis中调用 incr命令,如果返回值>1 说明秒杀重复了
     *
     * @param seckillOrderAddDTO userId SeckillOrderItemAddDTO(skuId)
     */
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public void seckillCommitCheck(SeckillOrderAddDTO seckillOrderAddDTO) {
        //组织一下代表用户,和秒杀商品的key值 seckill:{userId}:{skuId}
        String reSeckillKey = "seckill:"
                + seckillOrderAddDTO.getUserId() + ":"
                + seckillOrderAddDTO.getSeckillOrderItemAddDTO().getSkuId();
        //在redis调用对这个key的incr命令
        Long increment = stringRedisTemplate.opsForValue().increment(reSeckillKey);
        if (increment > 1) {
            //说明重复秒杀了
            throw new CoolSharkServiceException(
                    ResponseCode.CONFLICT, "当前用户重复秒杀");
        }
    }
}
